<template>
	<view>
		<view v-if="!full">
			<view class="box">
				<view class="left" @tap="toggle">
					<block v-if="playing.id">
						<view class="pic_square">
							<image :src="playing.picUrl"></image>
						</view>
						<view class="pic_round" :class="status ? 'rotate' : ''">
							<image :src="playing.picUrl"></image>
						</view>
						<view class="info">
							<view>{{playing.name}}</view>
							<view>{{playing.singer}}</view>
						</view>
					</block>
					<block v-else>
						<view class="pic">
							<image src="../../static/tabBar/music_hl.png"></image>
						</view>
						<view class="info">
							<view>Music Cloud</view>
							<view>云音乐</view>
						</view>
					</block>
				</view>
				<view class="right">
					<view class="iconfont font_40" :class="status ? 'icon-zanting_o' : 'icon-bofang_o'" @tap="play"></view>
					<view class="iconfont icon-caidan_o font_40" @tap="open"></view>
				</view>
			</view>
		</view>
		
		<view v-else>
			<view class="full" :style="{height: screenHeight + 'px'}">
				<u-bar-height></u-bar-height>
				
				<view class="top_box">
					<view class="back" @tap="back" :style="{top: barHeight + 'px'}"><uni-icons type="left" size="26"></uni-icons></view>
					<view class="song_name">{{playing.name}} - {{playing.singer}}</view>
				</view>
				
				<view class="content_box">
					<view class="pic_box">
						<view class="pic-box-img"><image :src="playing.picUrl"></image></view>
						<view class="circle-ani"></view>
						<view class="circle-ani ani2"></view>
					</view>
					<view class="lyric_box" :style="{height: lyricHeight + 'px'}">
						<scroll-view :scroll-top="scrollTop" scroll-y="true" class="scroll-Y" ref="lyrics" :style="{height: lyricHeight +'px'}" :show-scrollbar="true">
							<view :class="{each:true, choose: (key == lyricIndex)}"  v-for="(item, key, index) in playing.songLyric" :key="key">{{item}}</view>
						</scroll-view>
					</view>
				</view>
				
				<view class="footer">
					<view class="control_btn">
						<view class="iconfont icon-aixin"></view>
						<view class="iconfont icon-xiazai"></view>
						<view class="iconfont icon-liuyanjianyi" @tap="show(playing.id)"></view>
					</view>
					<view class="control_slider"><slider :value="current" :max="time" block-size="0"/></view>
					<view class="control_btn">
						<view class="control_btn_left" @tap="playModel">
							<block v-if="playStatus == 1">
								<view class="iconfont icon-suijibofang01"></view>
							</block>
							<block v-else-if="playStatus == 2">
								<view class="iconfont icon-shunxubofang"></view>
							</block>
							<block v-else>
								<view class="iconfont icon-danquxunhuan"></view>
							</block>
							
						</view>
						<view class="control_btn_center">
							<view class="iconfont icon-anniu_jiantouxiangzuo_o" @tap="toggleSong('upper')"></view>
							<view :class="status ? 'iconfont icon-zanting_o' : 'iconfont icon-bofang_o'" @tap="play"></view>
							<view class="iconfont icon-anniu-jiantouxiangyou_o" @tap="toggleSong('next')"></view>
						</view>
						<view class="control_btn_right" @tap="open">
							<view class="iconfont icon--caidan"></view>
						</view>
					</view>
				</view>
				
			</view>
		</view>
		
		<view class="songPopup">
			<uni-popup ref="songPopup" type="bottom">
				<uni-section :title="currentIndex ? '歌单列表' : '最近播放'"  type="line"></uni-section>
				<view class="popup-content">
					<swiper class="swiper" :indicator-dots="true" style="height: 300px;" @change="changeIndex">
						<swiper-item>
							<block v-if="playList.length">
								<scroll-view scroll-y="true" style="height: 300px;">
									<view class="list" v-for="(item, index) in playList" :key="index">
										<view class="list_left"  @tap="playSong(item)">
											<view>{{item.name}}</view>
											<view>{{item.singer}}</view>
										</view>
										<view v-if="item.isPlay" class="iconfont icon-bofangzhong" style="color: green"></view>
										<view class="list_right" @tap="remove(item.id)">
											<view><uni-icons type="closeempty" size="26"></uni-icons></view>
										</view>
									</view>
								</scroll-view>
							</block>
							
							<block v-else>
								<view class="none">空空如也</view>
							</block>
						</swiper-item>
						<swiper-item>
							<block v-if="songSheetPlayList.length">
								<scroll-view scroll-y="true" style="height: 300px;">
									<view class="list" v-for="(item, index) in songSheetPlayList" :key="index">
										<view class="list_left"  @tap="playSong(item)">
											<view>{{item.name}}</view>
											<view>{{item.singer}}</view>
										</view>
										<view v-if="item.isPlay" class="iconfont icon-bofangzhong" style="color: green"></view>
										<view class="list_right" @tap="remove(item.id)">
											<view><uni-icons type="closeempty" size="26"></uni-icons></view>
										</view>
									</view>
								</scroll-view>
							</block>
							
							<block v-else>
								<view class="none">空空如也</view>
							</block>
						</swiper-item>
					</swiper>
					
					<view class="line"></view>
					<view class="list_btn margin_top_10" @click="cancel">关闭</view>
				</view>
			</uni-popup>
		</view>
		
		<u-popup-comment :list="comments" :total="total"></u-popup-comment>
	</view>
</template>

<script>
	import util from '@/utils/util.js';
	import { mapGetters, mapMutations } from 'vuex'
	import {comment, songUrl} from '@/API/API.js';
	export default {
		name:"u-player-control",
		
		data() {
			return {
				full: false,
				change: true,
				status: null,
				barHeight: 0,
				screenHeight: 667,
				lyricHeight: 200,
				playStatus: 1,
				playing: {},
				playList: [],
				songSheetPlayList: [],
				total: 0,
				comments: [],
				timer: 0,
				current: 0,
				scrollTop: 0,
				lyricIndex: 0,
				lyric: '',
				url: '',
				time: 0,
				innerAudioContext: null,
				currentIndex: 0
			};
		},
		
		mounted() {		
			this.playList = JSON.parse(util.getStorageSync('playList'));
			this.playStatus = this.$store.getters.playStatus;
			this.playing = this.$store.getters.playing;
			this.current = this.$store.getters.current;
			this.status = this.$store.getters.status;
			this.time = this.$store.getters.songTime;
			this.barHeight = getApp().globalData.barHeight;
			
			let _this = this;
			uni.getSystemInfo({
				success(data) {
					_this.screenHeight = data.screenHeight;
				}
			});
			
			uni.$on('playingUpdata', function(data) {
				_this.playing = data;
				_this.playSong(data);
			});
		},
		
		methods: {	 
			...mapMutations({
				setCurrent: 'SET_CURRENT',
				setPlaying: 'SET_PLAYING',
				setPlayingIndex: 'SET_PLAYING_INDEX',
				setPlayStatus: 'SET_PLAY_STATUS',
				setStatus: 'SET_STATUS',
				setSongTime: 'SET_SONG_TIME',
				setTimer: 'SET_TIMER'
			 }),
			 
			play(){
				if(this.playing.id){
					this.change = !this.change;
					this.status = !this.status;
					this.setStatus(this.status);
				}
			},
			
			open() {
				this.getPlayList();
				this.$refs.songPopup.open();
			},
			
			cancel(){
				this.$refs.songPopup.close();
			},
			
			toggle(){
				if(this.playing.id){
					this.full = true;
				}
			},
			
			back(){
				this.full = false;
			},
			
			getScrollHeight(){
				let heightArr = [];
				heightArr[0] = getApp().globalData.barHeight;
				const query = uni.createSelectorQuery().in(this);
				query.select('.top_box').fields({size: true})
				query.select('.pic_box').fields({size: true})
				query.select('.footer').fields({size: true})
				query.exec((data) => {
					data.forEach(val => {
						heightArr.push(val.height);
					});
				
					this.lyricHeight = util.scrollHeight(heightArr);
				})
			},
			
			getPlayList(){
				this.playList = JSON.parse(util.getStorageSync('playList'));
				this.songSheetPlayList = JSON.parse(util.getStorageSync('songSheetPlayList'));
			},

			playSong(item){
				if(this.timer){
					this.innerAudioContext.destroy();
				}
				
				this.playing = item;
				this.setPlaying(item);
				
				this.change = true;
				this.status = false;
				this.setStatus(false);
				
				if(this.currentIndex){
					let songSheetPlayList = JSON.parse(util.getStorageSync('songSheetPlayList'));
					songSheetPlayList.some(val => {
						if(val.id == item.id){
							val.isPlay = true;
						}else{
							val.isPlay = false;
						}
					});
					this.songSheetPlayList = songSheetPlayList;
					util.setStorageSync('songSheetPlayList', JSON.stringify(songSheetPlayList));
					
					this.playList.forEach((val, key) => {
						val.isPlay = false;
					});
					
					util.setStorageSync('playList', JSON.stringify(this.playList));
					
				}else{
					let playList = JSON.parse(util.getStorageSync('playList'));
					playList.some(val => {
						if(val.id == item.id){
							val.isPlay = true;
						}else{
							val.isPlay = false;
						}
					});
					this.playList = playList;
					util.setStorageSync('playList', JSON.stringify(playList));
					
					this.songSheetPlayList.forEach((val, key) => {
						val.isPlay = false;
					});
					
					util.setStorageSync('songSheetPlayList', JSON.stringify(this.songSheetPlayList));
				}
				
				setTimeout(() => {
					this.play();
				}, 2000);
				
			},
			
			remove(id){
				this.playList.some((val, key) => {
					if(val.id == id){
						if(key === 0){
							if(val.isPlay){
								if(this.playList.length == 1){
									this.playList[key].isPlay = true;
									uni.$emit('playingUpdata',{});
								}else{
									this.playList[key+1].isPlay = true;
									uni.$emit('playingUpdata',this.playList[key+1]);
								}
							}
						}else if(key === this.playList.length - 1){
							if(val.isPlay){
								this.playList[key-1].isPlay = true;
								uni.$emit('playingUpdata',this.playList[key-1]);
							}
						}else{
							if(val.isPlay){
								this.playList[key+1].isPlay = true;
								uni.$emit('playingUpdata',this.playList[key+1]);
							}
						}
						this.playList.splice(key, 1);
					}
				});
				
				util.setStorageSync('playList', JSON.stringify(this.playList));
				
			},
			
			changeIndex(e){
				this.currentIndex = e.detail.current;
			},
			
			show(id){
				comment({id: id, type: 2}).then(data => {
					this.commentCount = data.total;
					this.total = data.total;
					data.hotComments.forEach((val,key) => {
						data.hotComments[key].time = util.formatDate(val.time);
					});
					this.comments = data.hotComments;
					
					uni.$emit('popupComment', 'popupComment')
				});
			},
			
			toggleSong(type){
				console.log(type)
				let index = this.$store.getters.playingIndex;
				
				if(type == 'upper'){
					if(index == 0){
						return uni.showToast({ title: '已是第一首', icon: 'none'});
					}
					
					index --;
				}else{
					if(index == this.playList.length - 1){
						return uni.showToast({ title: '已是最后一首', icon: 'none'});
					}
					
					index ++;
				}
				
				this.playList.some((val, key) => {
					if(index == key){
						val.isPlay = true;
					}else{
						val.isPlay = false;
					}
				});
				
				util.setStorageSync('playList', JSON.stringify(this.playList));
				this.setPlayingIndex(index);
				
				this.playSong(this.playList[index]);
			},
			
			playModel(){
				let statu = this.playStatus;
		
				switch(statu){
					case '1':
						statu = '2';
					break;
					case '2':
						statu = '3';
					break;
					case '3':
						statu = '1';
					break;
				}
				this.playStatus = statu;
				console.log(this.playStatus)
				this.setPlayStatus(statu);
				util.setStorageSync('playModel', statu);
			},
			
			songUrl(id){
				this.url = '';
				songUrl({id: id}).then(data => {
					this.url = data.data[0].url;
					this.time = Math.trunc(data.data[0].time / 1000);
					this.setSongTime(this.time);
				});
			},
			
			createAudio(src){				
				const innerAudioContext = uni.createInnerAudioContext();
				innerAudioContext.src = src;
				 
				 this.innerAudioContext = innerAudioContext;
				
				this.innerAudioContext.onError((err) => {
				  console.log(err);
				});

				this.innerAudioContext.onEnded(() => { 
					switch(this.playStatus){
						case '1':
							console.log('随机播放')
							let index = Math.floor(Math.random() * this.playList.length);
							if(this.playList[index].id == this.playing.id){
								index = Math.floor(Math.random() * this.playList.length);
							}
							this.setPlayingIndex(index);
							this.playSong(this.playList[index]);
						break;
						case '2':
							console.log('顺序播放')
							let key = this.$store.getters.playingIndex;
							if(key == this.playList.length - 1)
								key = 0;
							else
								key ++;

							this.setPlayingIndex(key);
							this.playSong(this.playList[key]);
						break;
						case '3':
							console.log('单曲循环')
							this.current = 0;
							this.scrollTop = 0;
							this.lyricIndex = 0;
							
							this.innerAudioContext.play();
						break;
						default:
							console.log('出错了...')
					}
				});
			},
			
		},
		
		watch: {
			full(newVal){
				if(newVal){
					uni.hideTabBar();
					setTimeout(()=>{
						this.getScrollHeight();
					}, 400)
				}else{
					uni.showTabBar();
				}
			},
			
			current(newVal){
				let i = 0
				for (let key in this.playing.songLyric) {
					// key表示歌词对象中的时间，如果key等于歌曲进度value，改变当前歌词进度		lyricIndex
					if (+key == this.current) {
						this.lyricIndex = key;
						// 当歌词进度大于4，即播放到了4句歌词，开始滚动
						if (i > 4) {
							this.scrollTop = 24 * (i - 4);
						}
					}
					i++;
				}
			},
			
			playing(newVal, oldVal){
				if(JSON.stringify(newVal) != "{}"){
					console.log('url...')
					this.songUrl(this.playing.id);
				}
			},
			
			status(newVal){
				if(newVal){
					this.timer = setInterval(() => {
						this.current ++;
						this.setCurrent(this.current);
					}, 1000);
				}else{
					clearInterval(this.timer);
					this.setCurrent(0);
					this.current = 0;
					this.scrollTop = 0;
					this.lyricIndex = 0;
				}
			},
			
			url(newVal){
				if(newVal){
					console.log('status...')
					this.createAudio(this.url);
				}
			},
			
			change(newVal){
				if(newVal){
					console.log('stop...')
					this.innerAudioContext.pause();
				}else{
					console.log('play...')
					this.innerAudioContext.play();
				}
			}
		}
	}
</script>

<style scoped>
	@import url("../../static/css/iconfont.css");
	.box{
		height: 50px;
		display: flex;
		padding: 0 10px;
	}
	
	.left{
		width: 80%;
		height: 100%;
		display: flex;
		align-items: center;
	}
	
	.left .pic_square{
		width: 56px;
		height: 50px;
	}
	
	.left .pic_square image,
	.left .pic_round image,
	.left .pic image {
		width: 100%;
		height: 100%;
	}
	
	.left .pic_round{
		width: 46px;
		height: 46px;
		margin-left: -10%;
		z-index: -1;
	}
	
	.left .pic_round image {
		border-radius: 50%;
	}

	
	.left .pic{
		width: 30px;
		height: 30px;
		padding: 0 10px;
	}
	
	.rotate{
		animation:turn 8s linear infinite;   
	}
	
	@keyframes turn{
	  0%{-webkit-transform:rotate(0deg);}
	  25%{-webkit-transform:rotate(90deg);}
	  50%{-webkit-transform:rotate(180deg);}
	  75%{-webkit-transform:rotate(270deg);}
	  100%{-webkit-transform:rotate(360deg);}
	}
	
	.left .info{
		width: 168px;
		font-size: 13px;
		margin-left: 2%;
	}
	
	.left .info view:first-child{
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
	}
	
	.right{
		width: 24%;
		height: 100%;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}
	
	.popup-content{
		width: 100%;
		background-color: #fff;
		z-index: 99;
	}
	
	.popup-content .list{
		width: 90%;
		display: flex;
		justify-content: space-between;
		align-items: center;
		font-size: 14px;
		text-align: center;
		padding: 10px 20px;
	}
	
	.popup-content .line{
		height: 6px;
		background-color: #eaeaec;
	}
	
	.list_left {
		width: 70%;
		display: flex;
		flex-direction: column;
		text-align: left;
	}
	
	.list_right {
		display: flex;
		padding: 4px 8px;
	}
	
	.list_btn{
		text-align: center;
		padding: 10px 0;
	}
	
	.full{
		width: 100%;
		position: fixed;
		top: 0;
		left: 0;
		background-color: #000;
		z-index: 9;
	}
	
	.back{
		position: absolute;
		top: 0;
		left: 0;
		width: 8%;
		padding: 10px;
		z-index: 999;
	}
	
	.top_box{
		height: 40px;
		display: flex;
		align-items: center;
	}
	
	.song_name{
		width: 100%;
		height: 100%;
		line-height: 38px;
		text-align: center;
		white-space: nowrap;
		font-size: 13px;
		color: #fff;
	}
	
	.content_box .pic_box{
		width: 200px;
		height: 200px;
		position: relative;
		top: 0;
		left: 50%;
		transform: translate(-100px, 12px);
	}
	
	.content_box .pic_box .pic-box-img{
		width: 200px;
		height: 200px;
		border-radius: 50%;
		border: 5px solid rgba(83,77,93,.9);
		position: absolute;
		top: -5px;
		left: -5px;
	}
	
	.content_box .pic_box .pic-box-img image{
		width: 100%;
		height: 100%;
		border-radius: 50%;
	}
	
	.content_box .pic_box .circle-ani{
		width: 200px;
		height: 200px;
		position: absolute;
		top: 0;
		left: 0;
		-webkit-border-radius: 50%;
		border-radius: 50%;
		border: 1px solid rgba(75,80,116,.6);
		-webkit-box-sizing: border-box;
		box-sizing: border-box;
		-webkit-transform: scale(1.1);
		transform: scale(1.1);
	}
	
	.content_box .pic_box .ani2 {
	       border: 1px solid rgba(75,80,116,.3);
	       -webkit-transform: scale(1.2);
	       transform: scale(1.2);
	}
	
	.content_box .lyric_box{
		width: 70%;
		margin: 0 auto;
		color: #fff;
		font-size: 13px;
		line-height: 1.6;
		padding: 34px 0 0 0;
		overflow: hidden;
		overflow-y: scroll;
	}
	
	.lyric_box .each{
		line-height: 2;
		text-align: center;
		font-size: 12px;
	}
	
	.lyric_box .choose {
		font-size: 14px;
		color: #efcb19;
	}
	
	.footer{
		width: 100%;
		padding-bottom: 0;
		padding-bottom: constant(safe-area-inset-bottom);
		padding-bottom: env(safe-area-inset-bottom); 
	}
	
	.footer .control_btn{
		display: flex;
		justify-content: space-around;
		align-items: center;
		color: #fff;
	}
	
	.footer .control_btn_left{
		flex: 1;
		height: 36px;
		line-height: 36px;
		text-align: center;
	}
	
	.footer .control_btn_center{
		flex: 4;
		display: flex;
		justify-content: space-evenly;
		align-items: center;
		margin: 0 auto;
	}
	
	.footer .control_btn_center view:nth-child(2){
		font-size: 60px !important;
	}
	
	.footer .control_btn_center view:first-child,
	.footer .control_btn_center view:last-child {
		font-size: 40px !important;
	}
	
	.footer .control_btn_right{
		flex: 1;
		height: 36px;
		line-height: 36px;
		text-align: center;
	}
	
	.none{
		text-align: center;
		font-size: 14px;
		font-weight: bold;
		padding: 20px 0;
	}
	
	/deep/.list_left{
		font-size: 12px;
	}
	
	/deep/.list_left view:first-child{
		font-size: 13px;
		font-weight: bold;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
	}
</style>